import React, { FC, useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { connect } from 'react-redux';
import { Button, Toast, Picker, List, Icon } from 'antd-mobile-v2';
import styles from './index.module.less';
import { createForm } from '@/components/rc-form';
import { Props } from '../../../type';
import { PRICE_TYPE } from '@/pages/official-doc/constants';
import {
  getRucStandardList,
  getMatterStandardUnit
} from '@/services/laber-declare';
import { DEFAULT_CHOOSE_LIST, DEFAULT_CHOOSE_COUNT } from '@/constants/common';
import _ from 'lodash';
import moment from 'moment';
import { RadioSelect } from '@/plugins/form/form-components/radio-select/view';
import { Input } from '@/plugins/form/form-components/input/view';
import { InputNumber } from '@/plugins/form/form-components/input-number/view';
import { InputMoney } from '@/plugins/form/form-components/input-money/view';
import { TextArea } from '@/plugins/form/form-components/textarea/view';
import { WrapFormItem } from '@/plugins/form/form-components/common/form-item/formItem-decorate';
import { clearRouteBlocker } from '@/components/form-group/route-blocker';
import { FormatDictData } from '@/utils/formatter';
import CheckboxSelectModal from '@/components/CheckboxSelectModal';
import { useKeyboardPops } from '@/hooks/use-keyboard-pop';
import RangeDatePicker from '@/components/rangedatepicker';
const CheckboxSelectModalWrap = WrapFormItem(CheckboxSelectModal);
const RadioSelectWrap = WrapFormItem(RadioSelect);
const InputWrap = WrapFormItem(Input);
const InputNumberWrap = WrapFormItem(InputNumber);
const InputMoneyWrap = WrapFormItem(InputMoney);
const TextAreaWrap = WrapFormItem(TextArea);

export interface AddModal extends Props {
  onCancel?: (needRefresh?: boolean) => void;
  loading?: boolean;
  onRefresh?: () => void;
  onRefreshStatus?: () => void;
  form: any;
  location: any;
  mattersList: Array<any>;
  onCloseModal: (params: any) => void;
  showDetailModal?: boolean;
  isEditing?: boolean;
  currentCostTypes: string[];
  visible: boolean;
}
interface UserOptions {
  text: string;
  value: string;
  name: string;
  departmentName: string;
}

interface RelatedOptions {
  text: string;
  value: string;
  priceType: number;
  maxPrice?: number;
  unit?: number;
  matterId: string;
  matterName: string;
}

interface StudentCode {
  name: string;
  departmentName: string;
  value: string;
  text: string;
}

const DEFAULT_OPTIONS = DEFAULT_CHOOSE_LIST.map(
  (item: { label: string; value: number }) => {
    return {
      text: item.label,
      value: item.value
    };
  }
);

const addModal: FC<AddModal> = (props) => {
  const [isAction] = useState(false);
  const [usersOptions, setUsersOptions] = useState<UserOptions[]>([]);
  const [relatedOptions, setRelatedOptions] = useState<RelatedOptions[]>([]);
  const [unitOptions, setUnitOptions] = useState([]);
  const [standardOptions, setStandardOptions] = useState(DEFAULT_OPTIONS);
  const [isAllowCustom, setIsAllowCustom] = useState(false);
  const [price, setPrice] = useState<number | undefined>(props.value?.price);
  const [quantity, setSize] = useState<number | undefined>(
    props.value?.quantity
  );

  const [el, setEl] = useState(null);
  useEffect(() => {
    const dom = document.createElement('div');
    dom.setAttribute('class', 'modal-container');

    document.body.appendChild(dom);
    setEl(dom);
    return () => {
      document.body.removeChild(dom);
    };
  }, []);

  const [standard, setRelatedRule] = useState<{
    [index: string]: any;
  }>();
  const [tipsText, setTipsText] = useState<string>('');
  const { open: isKeyboardPop, originHeight } = useKeyboardPops();
  //  请求页面中标准单位字典的列表
  const getMatterUnitList = async () => {
    const matterData = await getMatterStandardUnit();
    const { list: matterList } = FormatDictData(
      matterData.data,
      'uint',
      'meaning'
    );
    const options = matterList.map((item: { label: string; value: number }) => {
      return {
        text: item.label,
        value: item.value
      };
    });
    setUnitOptions(options);
    getRelateOptions(options);
  };
  useEffect(() => {
    getMatterUnitList();
  }, []);
  useEffect(() => {
    // getUsersOptions();
    if (props.form) {
      props.form.setFieldsValue({
        hasStandard: { text: '是', value: 1 }
      });
      clearRouteBlocker();
    }
  }, []);

  useEffect(() => {
    setAmount();
  }, [price, quantity, standard]);

  useEffect(() => {
    if (props.value) {
      props.form?.setFieldsValue({
        studentCode: props.value.studentCode,
        hasStandard: props.value.standard?.value
          ? { text: '是', value: 1 }
          : { text: '否', value: 0 },
        // standard: props.value.standard,
        quantity: props.value.quantity,
        provideAmount: props.value.provideAmount,
        unit: props.value.unit,
        remark: props.value.remark,
        startTime: props.value.startTime,
        endTime: props.value.endTime
      });
      setTimeout(() => {
        props.form?.setFieldsValue({
          price: props.value.price 
        });
      }, 0);
      clearRouteBlocker();
    }
  }, [props.value]);

  useEffect(() => {
    if (relatedOptions?.length === 1) {
      // 已选事项下只有一个标准,预填入；
      props.form?.setFieldsValue({
        standard: {
          text: relatedOptions[0].text,
          value: relatedOptions[0].value,
          matterId: relatedOptions[0].matterId,
          matterName: relatedOptions[0].matterName
        }
      });
      const curRule = getSelectItem('standard', relatedOptions);
      props.form?.setFieldsValue({
        matterId: curRule?.matterId
      });
      setRelatedRule(curRule);
    } else if (relatedOptions?.length > 1) {
      // 若有多个标准
      if (props.value?.standard) {
        // 若是已添加数据回填
        props.form?.setFieldsValue({
          standard: formateStandard(props.value)
        });
      } else if (props.preSelectStandard?.value) {
        // 若有多个标准，再次添加，预填上一次填写的
        const selectStandard = relatedOptions.find(
          (item: any) => item.value === props.preSelectStandard.value
        );
        selectStandard &&
          props.form?.setFieldsValue({
            standard: {
              text: selectStandard.text,
              value: selectStandard.value,
              matterId: selectStandard.matterId,
              matterName: selectStandard.matterName
            }
          });
      }
      // else {
      //   // 若有多个标准，第一次添加，预填第一个；
      //   props.form?.setFieldsValue({
      //     standard: {
      //       text: relatedOptions?.[0].text,
      //       value: relatedOptions?.[0].value,
      //       matterId: relatedOptions[0].matterId,
      //       matterName: relatedOptions[0].matterName
      //     }
      //   });
      // }
      const curRule = getSelectItem('standard', relatedOptions);
      props.form?.setFieldsValue({
        matterId: curRule?.matterId
      });
      setRelatedRule(curRule);
    }
    if (props.value) {
      setTimeout(() => {
        props.form?.setFieldsValue({
          price: props.value.price
        });
        clearRouteBlocker();
      }, 0);
    }
    clearRouteBlocker();
  }, [relatedOptions, props.preSelectStandard]);

  useEffect(() => {
    getTipsText();
  }, [props.visible]);

  // 根据费别、二级费别获取提示消息
  const getTipsText = () => {
    const [costType, secondCostType] = props.currentCostTypes;
    switch (costType) {
      // 劳务费->118 校工会劳务->300 后勤集团劳务->301 党费劳务->302 稿费->120 翻译费->121 审稿费->122 其他->303 绩效支出->123
      case '118':
      case '300':
      case '301':
      case '302':
        setTipsText('');
        break;
      case '120':
        setTipsText(
          '请在备注中写明稿件名称、字数（非必填）、录稿刊物名称、期号（非必填）。'
        );
        break;
      case '121':
        setTipsText('请在备注中写明翻译内容或标题。');
        break;
      case '122':
        setTipsText(
          '请在备注中写明稿件名称、字数（非必填）、录稿刊物名称（非必填）、期号（非必填）。'
        );
        break;
      case '303':
        setTipsText('请上传相关证明材料。');
        break;
      case '123':
        switch (secondCostType) {
          // 数据录入->1231 资料收集整理->1232 访谈->1233 发放问卷->1234 实验/建模->1235 
          // 撰写报告->1236 稿费->1237 翻译费->1238 审稿费->1239
          case '1231':
          case '1232':
          case '1233':
          case '1234':
          case '1235':
          case '1236':
            setTipsText(
              '请上传在职人员绩效工资统计表（科研系统打印、印有科研部门对口管理老师姓名的水印）。'
            );
            break;
          case '1237':
            setTipsText(
              '请在备注中写明稿件名称、字数（非必填）、录稿刊物名称、期号（非必填），并上传在职人员绩效工资统计表（科研系统打印、印有科研部门对口管理老师姓名的水印）。'
            );
            break;
          case '1238':
            setTipsText(
              '请在备注中写明翻译内容或标题，并上传在职人员绩效工资统计表（科研系统打印、印有科研部门对口管理老师姓名的水印）。'
            );
            break;
          case '1239':
            setTipsText(
              '请在备注中写明稿件名称、字数（非必填）、录稿刊物名称（非必填）、期号（非必填），并上传在职人员绩效工资统计表（科研系统打印、印有科研部门对口管理老师姓名的水印）。'
            );
            break;
          default:
            setTipsText(
              '请上传在职人员绩效工资统计表（科研系统打印、印有科研部门对口管理老师姓名的水印）。'
            );
            break;
        }
        break;
      default:
        setTipsText('');
        break;
    }
  };
  const formateStandard = (value: any) => {
    if (value.standard?.label) {
      let name = '';
      if (value.standard?.matterName) {
        name = value.standard?.matterName;
      }
      return {
        text: `${value.standard.text}${value.price}${value.unit?.text}${name} `,
        value: value.standard.value,
        matterId: value.standard.matterId,
        matterName: value.standard.matterName
      };
    }
    return value.standard;
  };

  const getSelectItem = (code: string, options: any[]) => {
    return props.form.getFieldValue(code)
      ? options.filter((user: any) => {
        return props.form.getFieldValue(code).value === user.value;
      })[0]
      : {};
  };

  const setAmount = () => {
    const hasStandardRender = props.form.getFieldValue('hasStandard');
    if (hasStandardRender?.value === DEFAULT_CHOOSE_COUNT.NO) {
      const amount =
        parseFloat(((price * quantity * 100) / 100).toFixed(2)) || undefined;
      props.form?.setFieldsValue({
        provideAmount: amount
      });
      return;
    }
    if (
      standard?.priceType === PRICE_TYPE.FIXED &&
      standard?.maxPrice &&
      quantity
    ) {
      const amount =
        parseFloat(((standard.maxPrice * quantity * 100) / 100).toFixed(2)) ||
        undefined;
      props.form?.setFieldsValue({
        provideAmount: amount
      });
    } else if (price && quantity) {
      const amount =
        parseFloat(((price * quantity * 100) / 100).toFixed(2)) || undefined;
      props.form?.setFieldsValue({
        provideAmount: amount
      });
    }
  };

  const setRelateStandard = (standard: {text: string;value: number}) => {
    const timer = setTimeout(() => {
      props.form?.setFieldsValue({
        hasStandard: standard
      });
      clearTimeout(timer);
    },200);
  };

  // 获取关联标准
  const getRelateOptions = async (unitOptions: any) => {
    if (!props.matterId) {
      props.form?.setFieldsValue({
        hasStandard: { text: '否', value: 0 }
      });
      return;
    }

    const res = await getRucStandardList({ matterId: props.matterId });
    if (res.data) {
      const list = res.data?.map((item: any) => {
        const unit = unitOptions.filter(
          (optionItem: { value: number; text: string }) =>
            optionItem.value === item.unit
        )[0]?.text;
        const priceOption =
          item.priceType === 0
            ? `${item.maxPrice || ''}${unit || ''}`
            : `${item.minPrice}-${item.maxPrice}${unit || ''}`;
        return {
          value: item.id,
          text: `${item.standardName} ${priceOption} ${item.matterName || ''} `,
          ...item
        };
      });
      setRelatedOptions(list);

      if (props.mattersList &&
          Array.isArray(props.mattersList) &&
          props.mattersList.length
      ) {
        let allowCustom = false;
        for (let i = 0; i < props.mattersList.length; i++) {
          if (props.mattersList[i]?.isCustomStandard == 1) {
            allowCustom = true;
            setIsAllowCustom(allowCustom);

            break;
          }
        }

        // 不允许自定义则默认为 关联标准
        if (!allowCustom) {
          setStandardOptions(DEFAULT_OPTIONS.slice(0, 1));
          setRelateStandard({ text: '是', value: 1 });
        } else {
          if (list?.length === 0) {
            setRelateStandard({ text: '否', value: 0 });
          }else{
            setRelateStandard({ text: '是', value: 1 });
          }
          setStandardOptions(DEFAULT_OPTIONS);
        }
      }


    }
  };
  //获取收款人
  // const getUsersOptions = async () => {
  //   const payload = {};
  //   const res = await getStudentCodeList(payload);
  //   if (res.data) {
  //     const list = res.data.map((item: any) => {
  //       return {
  //         value: item.id,
  //         text: `${item.name}/${item.id}/${item.departmentName}`,
  //         ...item
  //       };
  //     });
  //     setUsersOptions(list);
  //   }
  // };

  const getColumns = () => {
    return [
      {
        title: '学号',
        key: 'studentCode',
        gaeaKey: 'gaea-radio-select',
        options: usersOptions
      },
      {
        title: '姓名',
        key: 'studentName',
        gaeaKey: 'gaea-inputitem'
      },
      {
        title: '部门名称',
        key: 'department',
        gaeaKey: 'gaea-inputitem'
      },
      {
        title: '是否关联标准',
        key: 'hasStandard',
        gaeaKey: 'gaea-radio-select'
      },
      {
        title: '选择标准',
        key: 'standard',
        gaeaKey: 'gaea-radio-select',
        options: relatedOptions
      },
      {
        title: '单价',
        key: 'price',
        gaeaKey: 'gaea-inputmoney'
      },
      {
        title: '单位',
        key: 'unit',
        gaeaKey: 'gaea-radio-select',
        options: unitOptions
      },
      {
        title: '数量',
        key: 'quantity',
        gaeaKey: 'gaea-inputnumber'
      },
      {
        title: '发放金额',
        key: 'provideAmount',
        gaeaKey: 'gaea-inputmoney'
      },
      {
        title: '备注',
        key: 'remark',
        gaeaKey: 'gaea-inputitem'
      }
    ];
  };

  const handleOk = async () => {
    const result = await props.form.getFieldsValue();

    await props.form.validateFields((err: any) => {
      if (err) {
        const columns = getColumns();
        for (let i = 0; i < columns.length; i++) {
          let firstMsg;
          for (const key in err) {
            if (columns[i].key === key) {
              firstMsg = err[key]?.errors[0].message;
              if (key === 'quantity' && props.form?.getFieldValue('quantity')) {
                Toast.fail(
                  '数量格式错误，请输入数字，整数部分最多可输入12位，最多可输入两位小数'
                );
                return firstMsg;
              }
              Toast.fail(firstMsg);
              return firstMsg;
            }
          }
        }
      }
    });

    result.studentCode = Array.isArray(result.studentCode)
      ? result.studentCode
      : [result.studentCode];

    if (price == 0) {
      Toast.fail('单价必须大于0');
      return;
    }
    const hasStandardOK = props.form.getFieldValue('hasStandard');
    if (
      hasStandardOK.value == DEFAULT_CHOOSE_COUNT.YES &&
      standard?.priceType === PRICE_TYPE.RANGE &&
      price
    ) {
      if (price > standard.maxPrice || price < standard.minPrice) {
        Toast.fail('请输入符合标准的单价');
        return;
      }
    }
    if (quantity == 0) {
      Toast.fail('数量必须大于0');
      return;
    }
    const reg = /^(\d{0,12}|0)((\.\d{1,2})?)$/;
    if (!reg.test(result['quantity'])) {
      Toast.fail(
        '数量格式错误，请输入数字，整数部分最多可输入12位，最多可输入两位小数'
      );
      return;
    }
    if (
      props.form.getFieldValue('provideAmount') > props.matterTotalUseAble &&
      props.matterTotalUseAble !== -1
    ) {
      Toast.fail(`${props.matterName}事项余额不足,请修改发放明细`);
      return;
    }
    if (
      props.form.getFieldValue('provideAmount') > props.authorizeAmountUsable
    ) {
      Toast.fail(`${props.projectName}项目余额不足,请修改发放明细`);
      return;
    }
    const startTime = props.form.getFieldValue('startTime');
    const endTime = props.form.getFieldValue('endTime');
    if (!startTime) {
      Toast.fail('请选择开始时间');
      return;
    }
    if (!endTime) {
      Toast.fail('请选择结束时间');
      return;
    }
    const hasStandardRender = props.form.getFieldValue('hasStandard');

    const regex = /^\d+\.\d+$/;
    let isSizeFloat;
    if (regex.test(String(quantity))) {
      isSizeFloat = true;
    } else {
      isSizeFloat = false;
    }
    const showRemark =
      !hasStandardRender ||
      hasStandardRender?.value === DEFAULT_CHOOSE_COUNT.NO ||
      isSizeFloat;
    if (showRemark && !props.form.getFieldValue('remark')) {
      Toast.fail('请输入备注');
      return;
    }
    if (!props.form.getFieldValue('price')) {
      // 选择标准时没有price，需要手动添加
      const target = result.standard.value;
      relatedOptions.some((item) => {
        if (item.value === target) {
          result.price = item.maxPrice;
          result.unit = unitOptions.filter(
            (unitItem: any) => unitItem.value === item.unit
          )?.[0]; // 传入的 unit 需要为对象类型
        }
      });
    }
    if (!props.form.getFieldValue('unit')) {
      // 选择标准时没有unit，需要手动添加
      const target = result.standard.value;
      relatedOptions.some((item) => {
        if (item.value === target) {
          result.unit = unitOptions.filter(
            (unitItem: any) => unitItem.value === item.unit
          )?.[0];
        }
      });
    }
    props.onCloseModal && props.onCloseModal(result);
  };

  const studentCodeChange = (val: any) => {
    const studentCode = val.map((item) => {
      return {
        value: item.id,
        text: `${item.name}/${item.id}/${item.departmentName}`,
        studentName: item.name,
        ...item
      };
    });

    props.form?.setFieldsValue({
      studentCode
    });
  };

  const hasStandardChange = () => {
    setPrice(undefined);
    setSize(undefined);
    props.form?.setFieldsValue({
      quantity: undefined,
      provideAmount: undefined,
      price: undefined
    });
  };

  const standardChange = () => {
    const curRule = getSelectItem('standard', relatedOptions);
    props.form?.setFieldsValue({
      matterId: curRule?.matterId
    });
    setRelatedRule(curRule);
  };

  const priceChange = (value: number) => {
    setPrice(value);
    if (value == 0) {
      Toast.fail('单价必须大于0');
    }
    const hasStandardPC = props.form.getFieldValue('hasStandard');
    if (
      hasStandardPC.value == DEFAULT_CHOOSE_COUNT.YES &&
      standard?.priceType === PRICE_TYPE.RANGE
    ) {
      if (value > standard.maxPrice || value < standard.minPrice) {
        Toast.fail('请输入符合标准的单价');
      }
    }
  };

  const sizeChange = (value: number) => {
    setSize(value);
    if (value == 0) {
      Toast.fail('数量必须大于0');
    }
  };

  const isFolat = (data) => {
    const regex = /^\d+\.\d+$/;
    let isSizeFloat = false;
    if (regex.test(String(data))) {
      isSizeFloat = true;
    }
    return isSizeFloat;
  };

  const onClose = () => {
    props.onCloseModal && props.onCloseModal('back');
  };

  const renderFormItem = () => {
    const hasStandardRender = props.form.getFieldValue('hasStandard');
    const standardRender = getSelectItem('standard', relatedOptions);
    props.form?.getFieldProps('matterId');

    const userExter = {
      externalOption: {
        url: '/api/studentCode/v1/studentCode/list/page',
        placeholder: '姓名/学号/部门',
        formatVal: {
          value: 'id',
          text: 'name,id,departmentName'
        }
      }
    };
    return (
      <div
        style={{
          height: originHeight + 'px'
        }}
      >
        <div className={styles.modalTitle}>
          {'发放明细'}
          <Icon type="cross" className={styles.closeIcon} onClick={onClose} />
        </div>
        <CheckboxSelectModalWrap
          name="收款人"
          code="studentCode"
          form={props.form}
          value={props.value}
          {...userExter}
          required
          submit={studentCodeChange}
          editSetting={{
            key: 'gaea-checkbox-select',
            name: 'CheckboxSelect',
            editors: []
          }}
          renderMode={props.renderMode}
          placeholder="请选择"
          disabledOption={(item) => item.verification === '0'}
        />

        {/* <CheckboxSelectModal
          modalStatus={visible}
          closeModal={closeModal}
          // submit={(isHandle: boolean, v: any[]) => onSelect(isHandle, v)}
          // receiveData={receiveData} // 表单回填的数据，使用时参考公文录入功能的表单回填写法
          type="dept" // 类型 'dept' | 'person' | 'all'
          mode="multiple" // 单选多选模式 'single' | 'multiple'
          submit={studentCodeChange}

        /> */}
        {/* <RadioSelectWrap
          name="收款人"
          code="studentCode"
          form={props.form}
          // options={usersOptions}
          {...userExter}
          onChange={studentCodeChange}

          editSetting={{
            key: 'gaea-radio-select',
            name: 'RadioSelect',
            editors: []
          }}
          renderMode={props.renderMode}
          placeholder="请选择"
        /> */}
        {/* <InputWrap
          name="姓名"
          code="studentName"
          form={props.form}
          editSetting={{ key: 'gaea-inputitem', name: 'InputItem', editors: [] }}
          renderMode={props.renderMode}
          placeholder="输入学号后自动带入"
        />
        <InputWrap
          name="部门名称"
          code="department"
          form={props.form}
          editSetting={{ key: 'gaea-inputitem', name: 'InputItem', editors: [] }}
          renderMode={props.renderMode}
          placeholder="输入学号后自动带入"
        /> */}
        <RadioSelectWrap
          name="是否关联标准"
          code="hasStandard"
          form={props.form}
          options={standardOptions}
          onChange={hasStandardChange}
          editSetting={{
            key: 'gaea-radio-select',
            name: 'RadioSelect',
            editors: []
          }}
          renderMode={props.renderMode}
          placeholder="请选择"
        />
        {hasStandardRender?.text === '是' ? (
          <RadioSelectWrap
            name="选择标准"
            code="standard"
            form={props.form}
            options={relatedOptions}
            onChange={standardChange}
            editSetting={{
              key: 'gaea-radio-select',
              name: 'RadioSelect',
              editors: []
            }}
            renderMode={props.renderMode}
            notFoundContent="暂无发放标准"
            placeholder="请选择"
          />
        ) : null}
        {!hasStandardRender || hasStandardRender?.text === '否' ? (
          <RadioSelectWrap
            name="单位"
            code="unit"
            form={props.form}
            options={unitOptions}
            editSetting={{
              key: 'gaea-radio-select',
              name: 'RadioSelect',
              editors: []
            }}
            renderMode={props.renderMode}
            placeholder="请选择"
          />
        ) : null}
        {!hasStandardRender ||
        hasStandardRender?.value === DEFAULT_CHOOSE_COUNT.NO ||
        standardRender?.priceType === PRICE_TYPE.RANGE ? (
            <InputMoneyWrap
              name="单价"
              code="price"
              form={props.form}
              maxLength={12}
              onChange={priceChange}
              editSetting={{
                key: 'gaea-inputmoney',
                name: 'InputMoney',
                editors: []
              }}
              renderMode={props.renderMode}
              placeholder="请输入"
            />
          ) : null}
        <InputNumberWrap
          name="数量"
          code="quantity"
          form={props.form}
          maxLength={12}
          onChange={sizeChange}
          editSetting={{
            key: 'gaea-inputnumber',
            name: 'InputNumber',
            editors: []
          }}
          renderMode={props.renderMode}
          placeholder="请输入"
        />
        <InputWrap
          name="发放金额"
          code="provideAmount"
          form={props.form}
          extra="元"
          disabled
          editSetting={{
            key: 'gaea-inputitem',
            name: 'InputItem',
            editors: []
          }}
          renderMode={props.renderMode}
          placeholder="填写数量后自动计算"
        />
        {/* <InputWrap
          name="备注"
          code="remark"
          form={props.form}
          required
          editSetting={{
            key: 'gaea-inputitem',
            name: 'InputItem',
            editors: []
          }}
          renderMode={props.renderMode}
          placeholder="请填写工作日期，未关联标准或数量输入小数时请说明原因"
        /> */}

        <RangeDatePicker
          form={props.form}
          required
          maxDate={moment().date(31).format('YYYY-MM-DD')}
          code={['startTime', 'endTime']}
          name={['开始时间', '结束时间']}
        >
        </RangeDatePicker>
        <TextAreaWrap
          name="备注"
          code="remark"
          form={props.form}
          required
          editSetting={{
            key: 'gaea-inputitem',
            name: 'InputItem',
            editors: []
          }}
          renderMode={props.renderMode}
          placeholder="请按下方提示填写备注或上传附件，关联标准选择否或数量输入小数时请说明原因"
        />
        {tipsText && <div className={styles.tips}>{tipsText}</div>}
      </div>
    );
  };

  return el ? (
    createPortal(
      <>
        <div className={styles.addModalWrapper}>
          {renderFormItem()}
          {isKeyboardPop && (
            <Button
              type="primary"
              className={styles.confirmBtn}
              loading={isAction}
              onClick={handleOk}
            >
              确定
            </Button>
          )}
        </div>
      </>,
      el
    )
  ) : (
    <>
      <div className={styles.addModalWrapper}>
        {renderFormItem()}
        {isKeyboardPop && (
          <Button
            type="primary"
            className={styles.confirmBtn}
            loading={isAction}
            onClick={handleOk}
          >
            确定
          </Button>
        )}
      </div>
    </>
  );
};

const AddModalWrapper = createForm({
  onValuesChange: (props: any, changed, all) => {
    if (!changed) return;
    if (!_.isEqual({ hasStandard: { text: '是', value: 1 } }, changed)) {
      window.routesBlockerList = ['laberDetailChange'];
    }
    props.onChange && props.onChange(props.index, changed, all);
  }
})(addModal);

export default connect()(AddModalWrapper);
